
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.RC;
using Apps.Models.RC;
using Apps.IBLL.RC;
using System.Data.Common;
using System.Data;

namespace Apps.BLL.RC
{
    public partial class RC_WEIGHINGBLL : Virtual_RC_WEIGHINGBLL, IRC_WEIGHINGBLL
    {


    }
    public class Virtual_RC_WEIGHINGBLL
    {
        [Dependency]
        public IRC_WEIGHINGRepository m_Rep { get; set; }

        public List<V_RC_WEIGHING> GetVWeighingList(ref GridPager pager, Expression<Func<V_RC_WEIGHING, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = db.V_RC_WEIGHING.Where(whereLambda);
                pager.totalRows = queryData.Count();
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return queryData.ToList();
            }
        }

        /// <summary>
        /// 拆分批次
        /// </summary>
        /// <param name="p_code">批次号</param>
        /// <param name="pu_code">上传批次号</param>
        /// <param name="p_ids">计量ID</param> 
        /// <returns></returns>
        public bool JL_CHANGE_CODE(ref ValidationErrors errors, string p_code, string pu_code, string p_ids)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    DbParameter[] par = {
                    db.CreateInParameter("P_CODE",DbType.AnsiString, p_code),
                    db.CreateInParameter("PU_CODE",DbType.AnsiString, pu_code),
                    db.CreateInParameter("P_STR",DbType.AnsiString, p_ids),
                    db.CreateInParameter("P_CHAR",DbType.AnsiString, ","),
                    db.CreateOutParameter("P_ERRCODE", DbType.AnsiString, 20),
                    db.CreateOutParameter("P_ERRINFO", DbType.AnsiString, 100)  };

                    var ret = db.ExecuteProduce("PCK_CARWEIGHT.CHANGE_CODE", par);
                    if (ret["P_ERRCODE"].ToString() != "0")  
                    {
                        errors.Add(ret["P_ERRINFO"].ToString());
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        /// <summary>
        /// 删除拆分批次
        /// </summary>
        /// <param name="p_code">批次号</param>
        /// <returns></returns>
        public bool JL_DELETE_CODE(ref ValidationErrors errors, string p_code)
        { 
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    DbParameter[] pars = {
                    db.CreateInParameter("P_CODE",DbType.AnsiString, p_code),
                    db.CreateOutParameter("P_ERRCODE", DbType.AnsiString, 20),
                    db.CreateOutParameter("P_ERRINFO", DbType.AnsiString, 100) };
                     
                    var ret = db.ExecuteProduce("PCK_CARWEIGHT.DELETE_CODE", pars);
                    if (ret["P_ERRCODE"].ToString() != "0")
                    {
                        errors.Add(ret["P_ERRINFO"].ToString());
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual List<RC_WEIGHINGModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<RC_WEIGHING> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.WEIGHING_ID.Contains(queryStr)
                                || a.PROCESS_ID.Contains(queryStr)


                                || a.GROSS_NODE_ID.Contains(queryStr)
                                || a.GROSS_USER_ID.Contains(queryStr)






                                || a.UPLOAD_BATCHCODE.Contains(queryStr)

                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<RC_WEIGHINGModel> GetPagerList(ref GridPager pager, Expression<Func<RC_WEIGHING, bool>> whereLambda)
        {

            IQueryable<RC_WEIGHING> queryData = m_Rep.GetList(whereLambda);

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<RC_WEIGHINGModel> GetPagerListByComb(ref GridPager pager, Expression<Func<RC_WEIGHING, bool>> whereLambda)
        {

            IQueryable<RC_WEIGHING> queryData = m_Rep.GetList();

            queryData = queryData.Where(whereLambda.Compile()).AsQueryable();

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<RC_WEIGHINGModel> GetList(Expression<Func<RC_WEIGHING, bool>> whereLambda)
        {

            IQueryable<RC_WEIGHING> queryData = m_Rep.GetList(whereLambda);

            return CreateModelList(ref queryData);
        }

        public virtual List<RC_WEIGHINGModel> GetListByComb(Expression<Func<RC_WEIGHING, bool>> whereLambda)
        {

            IQueryable<RC_WEIGHING> queryData = m_Rep.GetList();

            queryData = queryData.Where(whereLambda.Compile()).AsQueryable();

            return CreateModelList(ref queryData);
        }

        public virtual List<RC_WEIGHINGModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<RC_WEIGHINGModel>();
        }

        public virtual List<RC_WEIGHINGModel> CreateModelList(ref IQueryable<RC_WEIGHING> queryData)
        {

            List<RC_WEIGHINGModel> modelList = (from r in queryData
                                                select new RC_WEIGHINGModel
                                                {
                                                    WEIGHING_ID = r.WEIGHING_ID,
                                                    PROCESS_ID = r.PROCESS_ID,
                                                    GROSS_MODE = r.GROSS_MODE,
                                                    GROSS = r.GROSS,
                                                    GROSS_NODE_ID = r.GROSS_NODE_ID,
                                                    GROSS_USER_ID = r.GROSS_USER_ID,
                                                    GROSS_TIME = r.GROSS_TIME,
                                                    TARE = r.TARE,
                                                    NET = r.NET,
                                                    COEFFECENT = r.COEFFECENT,
                                                    CUTBILL = r.CUTBILL,
                                                    RADOM = r.RADOM,
                                                    BALANCE = r.BALANCE,
                                                    UPLOAD_BATCHCODE = r.UPLOAD_BATCHCODE,
                                                    UPLOAD_STATUS = r.UPLOAD_STATUS,

                                                }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, RC_WEIGHINGModel model)
        {
            try
            {
                RC_WEIGHING entity = m_Rep.GetById(model.WEIGHING_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new RC_WEIGHING();
                entity.WEIGHING_ID = model.WEIGHING_ID;
                entity.PROCESS_ID = model.PROCESS_ID;
                entity.GROSS_MODE = model.GROSS_MODE;
                entity.GROSS = model.GROSS;
                entity.GROSS_NODE_ID = model.GROSS_NODE_ID;
                entity.GROSS_USER_ID = model.GROSS_USER_ID;
                entity.GROSS_TIME = model.GROSS_TIME;
                entity.TARE = model.TARE;
                entity.NET = model.NET;
                entity.COEFFECENT = model.COEFFECENT;
                entity.CUTBILL = model.CUTBILL;
                entity.RADOM = model.RADOM;
                entity.BALANCE = model.BALANCE;
                entity.UPLOAD_BATCHCODE = model.UPLOAD_BATCHCODE;
                entity.UPLOAD_STATUS = model.UPLOAD_STATUS;
                entity.TARE_MODE = model.TARE_MODE;
                entity.TARE_NODE_ID = model.TARE_NODE_ID;
                entity.TARE_USER_ID = model.TARE_USER_ID;
                entity.TARE_TIME = model.TARE_TIME;

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<RC_WEIGHING, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.RC_WEIGHING.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }




        public virtual bool Edit(ref ValidationErrors errors, RC_WEIGHINGModel model)
        {
            try
            {
                RC_WEIGHING entity = m_Rep.GetById(model.WEIGHING_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.WEIGHING_ID = model.WEIGHING_ID;
                entity.PROCESS_ID = model.PROCESS_ID;
                entity.GROSS_MODE = model.GROSS_MODE;
                entity.GROSS = model.GROSS;
                entity.GROSS_NODE_ID = model.GROSS_NODE_ID;
                entity.GROSS_USER_ID = model.GROSS_USER_ID;
                entity.GROSS_TIME = model.GROSS_TIME;
                entity.TARE = model.TARE;
                entity.NET = model.NET;
                entity.COEFFECENT = model.COEFFECENT;
                entity.CUTBILL = model.CUTBILL;
                entity.RADOM = model.RADOM;
                entity.BALANCE = model.BALANCE;
                entity.UPLOAD_BATCHCODE = model.UPLOAD_BATCHCODE;
                entity.UPLOAD_STATUS = model.UPLOAD_STATUS;



                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }



        public virtual RC_WEIGHINGModel GetById(object id)
        {
            if (IsExists(id))
            {
                RC_WEIGHING entity = m_Rep.GetById(id);
                RC_WEIGHINGModel model = new RC_WEIGHINGModel();
                model.WEIGHING_ID = entity.WEIGHING_ID;
                model.PROCESS_ID = entity.PROCESS_ID;
                model.GROSS_MODE = entity.GROSS_MODE;
                model.GROSS = entity.GROSS;
                model.GROSS_NODE_ID = entity.GROSS_NODE_ID;
                model.GROSS_USER_ID = entity.GROSS_USER_ID;
                model.GROSS_TIME = entity.GROSS_TIME;
                model.TARE = entity.TARE;
                model.NET = entity.NET;
                model.COEFFECENT = entity.COEFFECENT;
                model.CUTBILL = entity.CUTBILL;
                model.RADOM = entity.RADOM;
                model.BALANCE = entity.BALANCE;
                model.UPLOAD_BATCHCODE = entity.UPLOAD_BATCHCODE;
                model.UPLOAD_STATUS = entity.UPLOAD_STATUS;

                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual RC_WEIGHINGModel GetItem(Expression<Func<RC_WEIGHING, bool>> whereLambda)
        {

            RC_WEIGHING entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            RC_WEIGHINGModel model = new RC_WEIGHINGModel();
            model.WEIGHING_ID = entity.WEIGHING_ID;
            model.PROCESS_ID = entity.PROCESS_ID;
            model.GROSS_MODE = entity.GROSS_MODE;
            model.GROSS = entity.GROSS;
            model.GROSS_NODE_ID = entity.GROSS_NODE_ID;
            model.GROSS_USER_ID = entity.GROSS_USER_ID;
            model.GROSS_TIME = entity.GROSS_TIME;
            model.TARE = entity.TARE;
            model.NET = entity.NET;
            model.COEFFECENT = entity.COEFFECENT;
            model.CUTBILL = entity.CUTBILL;
            model.RADOM = entity.RADOM;
            model.BALANCE = entity.BALANCE;
            model.UPLOAD_BATCHCODE = entity.UPLOAD_BATCHCODE;
            model.UPLOAD_STATUS = entity.UPLOAD_STATUS;

            return model;
        }


        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<RC_WEIGHINGModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.WEIGHING_ID, "WEIGHING_ID");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.PROCESS_ID, "PROCESS_ID");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.GROSS_MODE, "GROSS_MODE");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.GROSS, "GROSS");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.GROSS_NODE_ID, "GROSS_NODE_ID");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.GROSS_USER_ID, "GROSS_USER_ID");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.GROSS_TIME, "GROSS_TIME");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.TARE, "TARE");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.NET, "NET");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.COEFFECENT, "COEFFECENT");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.CUTBILL, "CUTBILL");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.RADOM, "RADOM");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.BALANCE, "BALANCE");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.TARE_MODE, "TARE_MODE");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.TARE_NODE_ID, "TARE_NODE_ID");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.TARE_USER_ID, "TARE_USER_ID");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.TARE_TIME, "TARE_TIME");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.UPLOAD_BATCHCODE, "UPLOAD_BATCHCODE");
            excelFile.AddMapping<RC_WEIGHINGModel>(x => x.UPLOAD_STATUS, "UPLOAD_STATUS");

            //SheetName
            var excelContent = excelFile.Worksheet<RC_WEIGHINGModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new RC_WEIGHINGModel();
                entity.WEIGHING_ID = row.WEIGHING_ID;
                entity.PROCESS_ID = row.PROCESS_ID;
                entity.GROSS_MODE = row.GROSS_MODE;
                entity.GROSS = row.GROSS;
                entity.GROSS_NODE_ID = row.GROSS_NODE_ID;
                entity.GROSS_USER_ID = row.GROSS_USER_ID;
                entity.GROSS_TIME = row.GROSS_TIME;
                entity.TARE = row.TARE;
                entity.NET = row.NET;
                entity.COEFFECENT = row.COEFFECENT;
                entity.CUTBILL = row.CUTBILL;
                entity.RADOM = row.RADOM;
                entity.BALANCE = row.BALANCE;
                entity.TARE_MODE = row.TARE_MODE;
                entity.TARE_NODE_ID = row.TARE_NODE_ID;
                entity.TARE_USER_ID = row.TARE_USER_ID;
                entity.TARE_TIME = row.TARE_TIME;
                entity.UPLOAD_BATCHCODE = row.UPLOAD_BATCHCODE;
                entity.UPLOAD_STATUS = row.UPLOAD_STATUS;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<RC_WEIGHINGModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        RC_WEIGHING entity = new RC_WEIGHING();
                        entity.WEIGHING_ID = model.WEIGHING_ID;
                        entity.PROCESS_ID = model.PROCESS_ID;
                        entity.GROSS_MODE = model.GROSS_MODE;
                        entity.GROSS = model.GROSS;
                        entity.GROSS_NODE_ID = model.GROSS_NODE_ID;
                        entity.GROSS_USER_ID = model.GROSS_USER_ID;
                        entity.GROSS_TIME = model.GROSS_TIME;
                        entity.TARE = model.TARE;
                        entity.NET = model.NET;
                        entity.COEFFECENT = model.COEFFECENT;
                        entity.CUTBILL = model.CUTBILL;
                        entity.RADOM = model.RADOM;
                        entity.BALANCE = model.BALANCE;
                        entity.UPLOAD_BATCHCODE = model.UPLOAD_BATCHCODE;
                        entity.UPLOAD_STATUS = model.UPLOAD_STATUS;

                        db.RC_WEIGHING.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
        public void Dispose()
        {

        }

    }
}
